package org.xlh.springboot.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.xlh.springboot.bean.User;

import java.io.IOException;
import java.nio.charset.Charset;

public class YamlMessageConverter extends AbstractHttpMessageConverter {

    //对象映射器
    private ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));


    //非常重要的一步，要将媒体类型text/yaml 和消息转换器进行绑定
    public YamlMessageConverter() {
        super(new MediaType("text", "yaml", Charset.forName("UTF-8")));
    }

    // 自定义的消息转换器，表示只有User类型的才支持消息转换
    @Override
    protected boolean supports(Class clazz) {
        return User.class.isAssignableFrom(clazz);
    }

    //将yaml格式的字符串转换为java对象
    @Override
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }


    //将java对象转换为yaml格式的字符串
    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        objectMapper.writeValue(outputMessage.getBody(), o);
    }
}
